Operator Overloading

방법 1.
class Edge{
public:
int node[2];
int distance;
Edge(int a, int b, int distance){
this->node[0]=a;
this->node[1]=b;
this->distance=distance;
}
int operator+(Edge& edge){
return this->distance+edge.distance;
}
};
// Edge e1=Edge(1, 7, 12);
// Edge e2=Edge(1, 4, 28);
// cout<< e1+e2<<"\n"; // e1.operator+(e2)
방법2.
class Edge{
public:
int node[2];
int distance;
Edge(int a, int b, int distance){
this->node[0]=a;
this->node[1]=b;
this->distance=distance;
}
int operator+(Edge& edge);
}
int Edge::operator+(Edge& edge){
return this->distance+edge.distance;
}
방법3
class Edge{
public:
int node[2];
int distance;
Edge(int a, int b, int distance){
this->node[0]=a;
this->node[1]=b;
this->distance=distance;
}
};
int operator+(Edge& edge1, Edge& edge2){
return edge1.distance+edge2.distance;
}
ex) vector
class Point{
private:
int xpos, ypos;
public:
Point(int x, int y):xpos(x), ypos(y){}
void ShowPosition(){
cout<<'['<<xpos<<','<<ypos<<']'<<endl;
}
Point operator+(const Point& ref){
Point pos(xpos+ref.xpos, ypos+ref.ypos);
return pos;
}
friend Point operator-(const Point&, const Point&);
};
Point operator-(const Point& pos1, const Point& pos2){
Point pos(poas1.xpos-pos2.xpos, pos1.ypos-pos2.ypos);
return pos;
}
int main(void){
Point pos1(3, 4);
Point pos2(10, 20);
Point pos3=pos1+pos2; // pos1.operator+(pos2)
Point pos4=pos1-pos2; // operator-(pos1, pos2)
pos3.ShowPosition();
pos4.ShowPosition();
return 0;
}